<template>
	<view class="pad-0-20" :class="{'no-scroll': popupVisible}">
		<!-- #ifdef APP -->
		<uni-nav-bar :border="false" color="#222" backgroundColor="transparent" title="" />
		<!-- #endif -->
		<view class="top-bg"></view>
		<view class="find-box">
			<view class="font-24 font-600 col-000-8">
				<!-- 热门播放 -->
				{{$t('grid.hotPlay')}}
			</view>
			<view class="play-list">
				<view class="item" v-for="(item, index) in playList" :key="index" @click="hotPlayDetail(item.id)"
					:style="{ background: item.background || 'rgba(0,0,0,0.4)' }">
					<!-- <view class="ico">
						<image class="w-100" src="/static/images/play-ico-1.png" mode="widthFix"></image>
					</view> -->
					<view class="play">
						<image class="w-100" src="/static/svg/play-btn.svg" mode="widthFix"></image>
					</view>
					<view>
						<view class="name font-14 font-500 col-fff">
							{{item.title}}
						</view>
						<view class="sub-name font-11">
							{{item.count}}{{$t('mine.pattern')}}
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="recommend-box m-t-20">
			<view class="font-24 font-600 col-000-8">
				<!-- 热门推荐 -->
				{{$t('grid.hotRecommend')}}
			</view>
			<scroll-view id="tab-bar" class="scroll-h" :scroll-x="true" :show-scrollbar="false" :scroll-into-view="scrollInto"
				scroll-with-animation>
				<view v-for="(tab,index) in tabBars" :key="tab.id" class="uni-tab-item font-14"
					:class="tabIndex==index ? 'active' : ''" :id="tab.id" :data-current="index" @click="ontabtap">
					{{tab.label}}
				</view>
			</scroll-view>
			<view class="my-collection">
				<view class="list">
					<view class="item shadow" v-for="(item, index) in collectList" :key="index" @click="doDetail(item)">
						<view class="t flex-center-center">
							<image class="img" :src="item.preview_image" mode="aspectFill"></image>
						</view>
						<view class="b">
							<view class="name font-14 col-000-8 ell">
								{{item.pattern_name}}
							</view>
							<view class="ico-collection" @click.stop="showCollect(item)">
								<uni-icons :type="item.isCollected ? 'star-filled' : 'star'" :color="item.isCollected ? '#FABD18' : '#666'" size="20"></uni-icons>
							</view>
						</view>
					</view>
				</view>
				<uni-load-more :status="loadStatus" :contentText="contentText"
					v-if="collectList.length > 0 &&collectList.length > params.limit"></uni-load-more>
			</view>
		</view>
		<view class="" style="width: 100%;height: 88rpx;">

		</view>

		<uni-popup ref="popup" type="bottom" border-radius="16px 16px 0 0" :safe-area-inset-bottom="true" :mask-click="false">
			<view class="pop-box pad-20" v-if="patternsDetail">
				<view class="flex flex-between flex-center">
					<view class="col-000-8 font-18 font-600">
						<!-- 图案详情 -->
						{{ $t('grid.patternDetails') }}
					</view>
					<view class="close" @click="closePopup">
						<uni-icons type="closeempty" color="rgba(0,0,0,0.4)" size="20"></uni-icons>
					</view>
				</view>
				<view class="img-box flex-center-center">
					<img class="img" :src="patternsDetail.preview_image" mode="widthFix"><img>
					<view class="collect" @click="doCollect">
						<uni-icons :type="isCollect ? 'star-filled' : 'star'" :color="isCollect ? '#FABD18' : '#666'"
							size="26"></uni-icons>
						<!-- <uni-icons type="star-filled" color="#fff" size="20"></uni-icons> -->
					</view>
				</view>
				<view class="col-000-8 font-24 font-600 text-center" style="margin-top: 48rpx;">
					{{patternsDetail.pattern_name}}
				</view>
				<view class="btn-box popup-btn-box">
					<view class="right shadow flex-center-center" @click="playAdd()">
						<uni-icons color="#fff" type="plusempty" size="20"></uni-icons>
					</view>
					<view class="center left flex-center-center" @click="playAll">
						<image class="img" src="/static/svg/play.svg" mode="widthFix"></image>
						<view class="col-fff font-14 font-500">
							<!-- 立即播放 -->
							{{ $t('grid.playNow') }}
			
						</view>
					</view>
					<view class="right shadow flex-center-center" @click="playAdd()">
						<image class="next" src="/static/svg/next.svg" mode=""></image>
					</view>
				</view>
			</view>
		</uni-popup>
		<selectCollect ref="ref_select_collect" @success="onCollectSuccess" @closePopup="closePopupSelect" />
		<!-- 立即播放全部 -->
		<selectDevice ref="ref_select_device" @choose="chooseDevice" />
		<!-- 添加到全部 -->
		<selectDevice ref="ref_select_device_add" @choose="chooseDeviceAdd" />
	</view>
</template>

<script>
	import selectCollect from '@/components/select-collect/index.vue'
	import selectDevice from '@/components/select-device/index.vue'
	import patternApi from "@/api/pattern.js";
	import statusBar from "@/uni_modules/uni-nav-bar/components/uni-nav-bar/uni-status-bar";
	import featuredPlaylistApi from "@/api/featured-playlist.js"
	import collectionApi from '@/api/collection';
	import playlistApi from '@/api/playlist';
	export default {
		components: {
			statusBar,
			selectDevice,
			selectCollect
		},
		data() {
			return {
				tabIndex: 0,
				scrollInto: "",
				tabBars: [],
				playList: [],
				collectList: [],
				category: '',
				params: {
					page: 1,
					limit: 20,
					total: 0
				},
				contentText: {
					contentdown: "轻轻上拉",
					contentrefresh: "加载中",
					contentnomore: "没有更多数据了",
				},
				patternsDetail: null,
				isCollect: false,
				collectIds: [], //收藏id数组
				popupVisible: false, // 弹窗显示状态
			}
		},
		onShow() {},
		onReachBottom() {
			this.getList();
		},
		onPullDownRefresh() {
			this.resetGetList()
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		onLoad() {
			this.contentText.contentdown = this.$t('loadContentText.contentdown');
			this.contentText.contentrefresh = this.$t('loadContentText.contentrefresh');
			this.contentText.contentnomore = this.$t('loadContentText.contentnomore');
			this.tabBars = uni.getStorageSync('pattern_category') || [];
			console.log("this.tabBars",this.tabBars)
			
			this.getList()
			this.getHotList()
			
			// 监听语言切换事件
			uni.$on('changeLanguage', this.onLanguageChange)
		},
		onUnload() {
			// 移除语言切换监听
			uni.$off('changeLanguage', this.onLanguageChange)
		},
		methods: {
			// 语言切换处理
			onLanguageChange() {
				console.log('[FEATURED-PLAYLIST] 语言已切换，重新加载数据')
				// 重新获取分类标签
				this.tabBars = uni.getStorageSync('pattern_category') || [];
				// 重新加载热门播放列表
				this.getHotList()
				// 重新加载图案列表
				this.resetGetList()
			},
			
			getHotList() {
				let params = {
					page: 1,
					limit: 20,
					language: uni.getStorageSync('CURRENT_LANG') || 'zh-Hans'
				}
				// 这里没做分页，后后续需求
				featuredPlaylistApi.getFeaturedPlaylists(params).then(res => {
					if (res.errCode === 0) {
						this.playList = res.data;
					}
				})
			},
			resetGetList() {
				this.collectList = [];
				this.params.page = 1;
				this.params.limit = 20;
				this.params.category = this.tabBars[this.tabIndex].value
				this.getList()
			},
			async getList() {
				let pageNo = this.params.page;
				let pageSize = this.params.limit;
				let totalpage = this.params.total;
				if (totalpage + 1 <= (pageNo - 1) * pageSize) {
					this.loadStatus = "nomore";
					return;
				}
				this.loadStatus = "loading";
				try {
					const res = await patternApi.getPatternList(this.params);
					if (res.errCode == 0) {
						const patterns = res.data.list;
						
						// 批量查询收藏状态
						if (patterns.length > 0) {
							const patternIds = patterns.map(p => p.id);
							try {
								const statusRes = await collectionApi.batchGetPatternsCollectionStatus({
									pattern_ids: patternIds
								});
								
								if (statusRes.errCode === 0) {
									// 为每个图案添加收藏状态
									patterns.forEach(pattern => {
										const status = statusRes.data[pattern.id];
										pattern.isCollected = status ? status.is_collected : false;
										pattern.collectionIds = status ? status.collection_ids : [];
									});
								}
							} catch (error) {
								console.error('批量查询收藏状态失败:', error);
								// 如果批量查询失败,设置所有图案为未收藏状态
								patterns.forEach(pattern => {
									pattern.isCollected = false;
									pattern.collectionIds = [];
								});
							}
						}
						
						this.collectList = this.collectList.concat(patterns);
						this.params.total = res.data.total;
						this.params.page = res.data.page + 1;
					}
					this.loadStatus = "loadmore";
				} catch (error) {
					console.error('获取图案列表失败:', error);
					this.loadStatus = "loadmore";
				}
			},
			hotPlayDetail(id) {
				uni.navigateTo({
					url: '/pages/featured-playlist/hot-play-detail?playlist_id=' + id
				})
			},
			ontabtap(e) {
				let index = e.target.dataset.current || e.currentTarget.dataset.current;
				this.switchTab(index);
			},
			ontabchange(e) {
				let index = e.target.current || e.detail.current;
				this.switchTab(index);
			},
			switchTab(index) {
				// if (this.newsList[index].data.length === 0) {
				// 	// this.getList(index);
				// }

				if (this.tabIndex === index) {
					return;
				}
				this.tabIndex = index;
				this.scrollInto = this.tabBars[index].id;

				this.resetGetList()
			},
			doDetail(item) {
				console.log('detail', item)
				this.patternsDetail = item;
				this.popupVisible = true;
				uni.hideTabBar();
				this.$refs.popup.open()
				// 根据id获取是否收藏
				collectionApi.getCollectionsByPattern({
					pattern_id: item.id
				}).then(res => {
					if (res.errCode === 0) {
						this.isCollect = res.data.length > 0 ? true : false;
						this.collectIds = res.data.map(item => item.id)
					}
				})
			},
			closePopup() {
				this.popupVisible = false;
				uni.showTabBar();
				this.patternsDetail = null;
				this.$refs.popup.close()
			},
			showCollect(item) {
				uni.hideTabBar();
				// 保存当前操作的图案(如果不是从弹窗点击的)
				if (!this.patternsDetail || this.patternsDetail.id !== item.id) {
					this.patternsDetail = item;
				}
				// 根据id获取是否收藏
				collectionApi.getCollectionsByPattern({
					pattern_id: item.id
				}).then(res => {
					if (res.errCode === 0) {
						this.isCollect = res.data.length > 0 ? true : false;
						this.collectIds = res.data.map(item => item.id)
						this.$refs.ref_select_collect.open(item.id, this.collectIds)
					}
				})
			},
			doCollect() {
				this.$refs.ref_select_collect.open(this.patternsDetail.id, this.collectIds)
			},
			onCollectSuccess(data) {
				uni.showTabBar()
				// 收藏成功后更新状态
				if (data.collectionIds && data.collectionIds.length > 0) {
					this.isCollect = true
					this.collectIds = data.collectionIds
					
					// 更新列表中对应图案的收藏状态
					if (this.patternsDetail) {
						const index = this.collectList.findIndex(item => item.id === this.patternsDetail.id);
						if (index !== -1) {
							this.collectList[index].isCollected = true;
						}
					}
				} else {
					this.isCollect = false
					this.collectIds = []
					
					// 更新列表中对应图案的收藏状态
					if (this.patternsDetail) {
						const index = this.collectList.findIndex(item => item.id === this.patternsDetail.id);
						if (index !== -1) {
							this.collectList[index].isCollected = false;
						}
					}
				}
			},
			closePopupSelect() {
				console.log('closePopupSelect')
				uni.showTabBar()
			},
			playAll() {
				this.$refs.ref_select_device.open()
			},
			playAdd() {
			  this.$refs.ref_select_device_add.open()
			},
			chooseDevice(sns) {
			console.log(this.patternsDetail)
			let patternIds = this.patternsDetail.id
			let params = {
				deviceSn: sns.length == 1 ? sns[0] : sns,
				patternIds: [patternIds]
			}
			playlistApi.playNow(params).then(res => {
				if(res.errCode === 0) {
						uni.showToast({
						  title: this.$t('grid.playingPattern') + ' ' + this.patternsDetail.pattern_name,
						  icon: 'none',
						  duration: 3000
						});
			      this.$refs.ref_select_device.closePopup()
			
					}
				})
			},
		chooseDeviceAdd(sns) {
			console.log(this.patternsDetail)
		  let patternIds = this.patternsDetail.id;
		  let params = {
		    deviceSn: sns.length == 1 ? sns[0] : sns,
		    patternIds: [patternIds]
		  }
		  playlistApi.batchAddPatternsToEnd(params).then(res => {
		    if(res.errCode === 0) {
			      uni.showToast({
			        title: this.$t('grid.playAdd'),
			        icon: 'none',
			        duration: 3000
			      });
			      this.$refs.ref_select_device_add.closePopup()
			
			    }
			  })
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import './common.scss';

	page.no-scroll {
		height: 100%;
		overflow: hidden;
	}
	
	.my-collection {
		width: 100%;
		margin-top: 80rpx;

		.list {
			width: 100%;
			display: flex;
			justify-content: space-between;
			align-items: flex-start;
			margin-top: 40rpx;
			flex-wrap: wrap;

			.item {
				width: 48%;
				margin-bottom: 32rpx;

				.t {
					width: 100%;
					height: 0;
					padding-bottom: 100%;
					position: relative;
					overflow: hidden;

					.img {
						position: absolute;
						top: 0;
						left: 0;
						width: 100%;
						height: 100%;
						border-radius: 100%;
						object-fit: cover;
					}
				}

				.b {
					height: 96rpx;
					padding: 24rpx 32rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					.name {
						width: 100%;
						height: 100%;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
						
					}
				}
			}
		}
	}

	.scroll-h {
		width: 100%;
		max-width: 100%;
		height: 68rpx;
		flex-direction: row;
		/* #ifndef APP-PLUS */
		white-space: nowrap;
		/* #endif */
		margin: 40rpx auto 0;
		overflow-x: auto;
		overflow-y: hidden;
	}

	.uni-tab-item {
		display: inline-block;
		min-width: 120rpx;
		padding: 0 10rpx;
		height: 68rpx;
		line-height: 68rpx;
		background-color: rgba(0, 0, 0, 0.08);
		border-radius: 34rpx;
		margin-right: 24rpx;
		text-align: center;
		color: rgba(0, 0, 0, 0.4);
		font-weight: 400;

		&.active {
			font-weight: 500;
			background-color: #000;
			color: #fff;
		}
	}


	.recommend-box {
		width: 100%;
	}

	.play-list {
		width: 100%;
		max-width: 100%;
		height: 300rpx;
		margin: 40rpx auto 0;
		overflow-x: auto;
		overflow-y: hidden;
		display: flex;
		justify-content: flex-start;
		-webkit-overflow-scrolling: touch;

		.item {
			width: 300rpx;
			height: 300rpx;
			min-width: 300rpx;
			flex-shrink: 0;
			border-radius: 16rpx;
			padding: 32rpx;
			position: relative;
			background-color: rgba(0, 0, 0, 0.4);
			margin-right: 30rpx;
			display: flex;
			align-items: flex-end;

			.ico {
				width: 88rpx;
				height: 88rpx;
				position: absolute;
				right: 36rpx;
				top: 36rpx;
			}

			.play {
				width: 80rpx;
				height: 48rpx;
				position: absolute;
				right: 32rpx;
				bottom: 32rpx;
			}

			.zan {
				width: 100%;
				height: 188rpx;
			}

			.name {
				text-align: left;
			}

			.sub-name {
				color: rgba(255, 255, 255, 0.4);
				margin-top: 8rpx;
			}
		}
	}

	.top-bg {
		width: 100%;
		height: 400rpx;
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		background-image: url(/static/images/common-bg-2.png);
		background-size: 100% 100%;
		z-index: 1;
	}

	.find-box {
		position: relative;
		z-index: 2;
		margin: 40rpx auto 0;
	}
</style>